<template>
  <div class="app-container">
    <div class="topBtn" style="margin-bottom:12px">
      <div style="display: flex">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['workflow:model:add']"
          size="mini">新增
        </el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['workflow:model:remove']" size="mini">删除
        </el-button>
        <el-button type="warning" icon="el-icon-download" @click="handleExport" v-hasPermi="['workflow:model:export']"
          size="mini">导出
        </el-button>
      </div>
      <el-input placeholder="请输入关键字" v-model="queryParams.modelName" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" type="primary" style="background: #2f54eb"
          @click="getList"></el-button>
      </el-input>
    </div>
    <el-table v-loading="loading" fit :data="modelList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模型名称" align="left" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleProcessView(scope.row)">
            <span>{{ scope.row.modelName }}</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属应用" align="center" prop="categoryName" :formatter="categoryFormat" />
      <el-table-column label="流程类型" align="center" prop="categoryName"
        :formatter="row => row.cronFlag === '1' ? '定时流程' : '普通流程'" />

      <el-table-column label="模型版本" align="center">
        <template slot-scope="scope">
          <el-tag size="medium">v{{ scope.row.version }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="left" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['workflow:model:edit']">修改
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-brush" @click="handleDesigner(scope.row)"
            v-hasPermi="['workflow:model:designer']">设计
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-video-play" v-hasPermi="['workflow:model:deploy']"
            @click.native="handleDeploy(scope.row)">部署
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" v-hasPermi="['workflow:model:remove']"
            style="color:red" @click.native="handleDelete(scope.row)">删除
          </el-button>
          <el-dropdown size="mini" v-hasPermi="[
            'workflow:model:query',
            'workflow:model:list',
            'workflow:model:remove',
          ]">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-view" @click.native="handleProcessRole(scope.row)"
                v-hasPermi="['workflow:model:role']">流程权限
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" @click.native="handleProcessView(scope.row)"
                v-hasPermi="['workflow:model:query']">流程图
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" @click.native="handleProcessTimed(scope.row)"
                v-if="scope.row.cronFlag === '1'">定时流程
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-price-tag" @click.native="handleHistory(scope.row)"
                v-hasPermi="['workflow:model:list']">历史
              </el-dropdown-item>
              <!-- <el-dropdown-item icon="el-icon-delete" @click.native="handleDelete(scope.row)"
                v-hasPermi="['workflow:model:remove']">删除
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!--  添加或修改模型信息对话框  -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body @close="cancel()" v-dialogDragWidth
      v-dialogDragHeight v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模型标识" prop="modelKey">
          <el-input v-model="form.modelKey" clearable disabled />
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" clearable :disabled="form.modelId !== undefined" />
        </el-form-item>
        <el-form-item label="所属应用" prop="category">
          <el-select v-model="form.category" placeholder="请选择" clearable style="width: 100%" disabled>
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
              :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="允许移动端发起" prop="permitAppStartFlag">
          <el-radio-group v-model="form.permitAppStartFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许移动端审批" prop="permitAppAuditFlag">
          <el-radio-group v-model="form.permitAppAuditFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="流程类型" prop="cronFlag">
          <el-radio-group v-model="form.cronFlag">
            <el-radio label="0">普通流程</el-radio>
            <el-radio label="1">定时流程</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 定时流程 -->
    <el-dialog title="定时流程" :visible.sync="timedProcessOpen" width="40%" :before-close="timedProcessClose">
      <el-alert title="请配置完成或修改流程后点击部署启动流程" type="warning">
      </el-alert>
      <!-- <Crontab ref="Crontab" :hideComponent="[]" /> -->
      <el-form ref="timedProcessRef" :model="timedProcessForm" :rules="timedProcessRules" label-width="100px"
        style="margin-top:12px">
        <el-form-item label="流程模型ID" prop="modelId">
          <el-input v-model="timedProcessForm.modelId" disabled />
        </el-form-item>
        <el-form-item label="定时模式" prop="crontab">
          <div @click="handleCronChange">
            <el-input v-model="timedProcessForm.crontab" readonly placeholder="请配置定时模式" />
          </div>
        </el-form-item>
        <el-form-item label="是否全员" prop="isAll">
          <el-radio-group v-model="timedProcessForm.isAll" @change="isAllChange">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType" v-if="timedProcessForm.isAll === '0'">
          <el-radio-group v-model="timedProcessForm.userType" @change="userTypeChange">
            <el-radio label="1">用户 </el-radio>
            <el-radio label="2">角色</el-radio>
            <el-radio label="3">部门</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="timedProcessForm.isAll === '0' && timedProcessForm.userType === '1'" label="发送用户"
          prop="userRange">
          <div @click="userOpenFun">
            <el-input v-model="timedProcessForm.userRangeName" readonly :placeholder="`请选择用户`" />
          </div>
        </el-form-item>
        <el-form-item v-if="timedProcessForm.isAll === '0' && timedProcessForm.userType === '2'" label="发送角色"
          prop="userRange">
          <el-select v-model="timedProcessForm.userRange" multiple placeholder="请选择角色" filterable style="width: 100%;">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="timedProcessForm.isAll === '0' && timedProcessForm.userType === '3'" label="发送部门"
          class="userTypeItem" prop="userRange">
          <tree-select :width="320" :height="400" :data="deptTreeData" :defaultProps="deptProps" multiple clearable
            placeholder="请选择部门" checkStrictly nodeKey="id" :checkedKeys="deptIds" @change="checkedDeptChange">
          </tree-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="timedProcessForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="timedProcessClose">取 消</el-button>
        <el-button type="primary" @click="timedProcessSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 流程图 -->
    <el-dialog :title="processView.title" :visible.sync="processView.open" width="70%" append-to-body>
      <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{ height: '400px' }" />
    </el-dialog>

    <el-dialog title="模型历史" :visible.sync="history.open" width="70%">
      <el-table v-loading="history.loading" fit :data="historyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模型标识" align="center" prop="modelKey" :show-overflow-tooltip="true" />
        <el-table-column label="模型名称" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-button type="text" @click="handleProcessView(scope.row)">
              <span>{{ scope.row.modelName }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="所属应用" align="center" prop="categoryName" :formatter="categoryFormat" />
        <el-table-column label="模型版本" align="center">
          <template slot-scope="scope">
            <el-tag size="medium">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-video-play" v-hasPermi="['workflow:model:deploy']"
              @click.native="handleDeploy(scope.row)">部署
            </el-button>
            <el-button type="text" size="mini" icon="el-icon-star-off" v-hasPermi="['workflow:model:save']"
              @click.native="handleLatest(scope.row)">设为最新
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="historyTotal > 0" :total="historyTotal" :page.sync="queryHistoryParams.pageNum"
        :limit.sync="queryHistoryParams.pageSize" @pagination="getHistoryList" />
    </el-dialog>

    <el-dialog :title="designerData.title" :visible.sync="designerOpen" append-to-body fullscreen>
      <process-designer :key="designerOpen" style="border: 1px solid rgba(0, 0, 0, 0.1)" ref="modelDesigner"
        :appId="designerData.appId" v-loading="designerData.loading" :bpmnXml="designerData.bpmnXml"
        :designerForm="designerData.form" @save="onSaveDesigner" />
    </el-dialog>
    <RoleModel :open="openProcessRole" v-if="openProcessRole" :close="() => (openProcessRole = false)"
      :row="rowProcessRole" />
    <CronUi ref="CronUi" @cronResult="cronResultValue" />
    <UserModel :fieldModel="{ userId: timedProcessForm.userRange && timedProcessForm.userRange.toString() }"
      :handleUserOrDept="handleUserOrDept" :open="userOpen" :close="userClose" chooseType="YES" v-if="userOpen" />

  </div>
</template>

<script>
import {
  getBpmnXml,
  historyModel,
  latestModel,
  addModel,
  updateModel,
  saveModel,
  delModel,
  deployModel,
  listAppModel,
  listModel,
  appProcessFormset,
  saveNodeInterface,
  saveAppProcessTitleConfig,
  settingCronModel,
  cronModelDetail
} from "@/api/workflow/model";
import { listCategory } from "@/api/workflow/category";
import ProcessDesigner from "@/components/ProcessDesigner";
import ProcessViewer from "@/components/ProcessViewer";
import { getToken } from "@/utils/auth";
import { saveNodeApproverProcess } from "@/api/app/electronicForms.js";
import RoleModel from "@/views/workflow/model/roleModel";
import CronUi from "@/components/Cron/cron-ui/index";
// import Crontab from "@/components/Crontab";
import UserModel from "@/components/userModel";
import TreeSelect from "@/components/TreeSelect";
import { deptTreeSelect } from "@/api/system/user";
import { listRole } from "@/api/app/role";



export default {
  name: "Model",
  components: {
    ProcessDesigner,
    ProcessViewer,
    RoleModel,
    CronUi,
    UserModel,
    TreeSelect,
    // Crontab
  },
  data() {
    return {
      deptTreeData: [],
      roleOptions: [],
      deptOptions: [],
      deptIds: [],
      deptProps: {
        children: "children",
        label: "label",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程模型表格数据
      modelList: [],
      categoryOptions: [],
      title: "",
      open: false,
      form: {
        permitAppStartFlag: '1',
        permitAppAuditFlag: '1',
        cronFlag: '0'
      },
      // 表单校验
      rules: {
        modelKey: [
          { required: true, message: "模型标识不能为空", trigger: "blur" },
        ],
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" },
        ],
        category: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
      },
      designerOpen: false,
      designerData: {
        loading: false,
        bpmnXml: "",
        modelId: null,
        form: {
          processName: null,
          processKey: null,
        },
      },
      designerModelId: null,
      processView: {
        title: "",
        open: false,
        index: undefined,
        xmlData: "",
      },
      // bpmn.xml 导入
      upload: {
        // 是否显示弹出层（xml导入）
        open: false,
        // 弹出层标题（xml导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        name: null,
        category: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/workflow/definition/import",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelKey: null,
        modelName: null,
        appId: null,
      },
      currentRow: null,
      history: {
        open: false,
        loading: false,
      },
      historyList: [],
      historyTotal: 0,
      queryHistoryParams: {
        pageNum: 1,
        pageSize: 10,
        modelKey: null,
      },
      openProcessRole: false,
      rowProcessRole: undefined,
      userOpen: false,
      timedProcessForm: {
        status: '1',
        isAll: '0',
        userType: '1',
        userRange: []
      },
      timedProcessOpen: false,
      timedProcessRules: {
        status: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "change" },
        ],
        userRange: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        crontab: [
          { required: true, message: "请配置定时表达式", trigger: "change" },
        ],
      },
    };
  },
  props: {
    appId: {
      type: String,
      default: "",
    },
  },
  created() {
    this.getCategoryList();
    this.getList();
  },
  methods: {

    /**
 * 查询部门下拉树结构（含部门前缀）
 */
    getDeptTreeData() {
      function refactorTree(data) {
        return data.map((node) => {
          let treeData = {
            id: node.id,
            label: node.label,
            parentId: node.parentId,
            weight: node.weight,
          };
          if (node.children && node.children.length > 0) {
            treeData.children = refactorTree(node.children);
          }
          return treeData;
        });
      }
      return new Promise((resolve, reject) => {
        this.getDeptOptions()
          .then(() => {
            this.deptTreeData = refactorTree(this.deptOptions);
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    /**
 * 查询部门下拉树结构
 */
    getDeptOptions() {
      return new Promise((resolve, reject) => {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data;
          resolve();
        });
      });
    },
    /**
 * 查询角色
 */
    getRoleOptions() {
      listRole().then((response) => (this.roleOptions = response.rows));
    },
    isAllChange(val) {
      this.timedProcessForm.userRange = []
      this.timedProcessForm.userRangeName = ''
      this.timedProcessForm.userType = val === '0' ? '1' : ''
    },
    userTypeChange(val) {
      this.timedProcessForm.userRange = []
      this.timedProcessForm.userRangeName = ''
      if (val === '2') {
        this.getRoleOptions()
      }
      if (val === '3') {
        this.getDeptTreeData()
      }
    },
    checkedDeptChange(checkedIds) {
      this.deptIds = checkedIds
      this.timedProcessForm.userRange = checkedIds
    },
    timedProcessClose() {
      this.timedProcessOpen = false
      this.timedProcessForm = {}
    },
    timedProcessSubmit() {
      this.$refs["timedProcessRef"].validate(async (valid) => {
        if (valid) {
          const params = { ...this.timedProcessForm }
          params.userRange = params.userRange.toString()
          const res = await settingCronModel(params)
          if (res.code === 200) {
            this.timedProcessOpen = false
            this.$message.success('配置成功')
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
        }

      })
    },
    async handleProcessTimed(row) {
      try {
        const res = await cronModelDetail(row.modelId)
        if (res.data && res.code === 200) {
          this.timedProcessForm = {
            modelId: res.data?.modelId,
            status: res.data?.status ?? '1',
            crontab: res.data?.crontab,
            isAll: res.data?.isAll ?? '0',
            userType: res.data?.userType ?? '1',
            userRange: res.data?.userRange,
          }

          if (res.data?.userType === '1') {
            const names = []
            res.data?.userRange.forEach(item => {
              names.push(item.name)
            })
            this.timedProcessForm.userRangeName = names.toString()
          }
          if (res.data?.userType === '2') {
            this.getRoleOptions()
          }
          if (res.data?.userType === '3') {
            this.getDeptTreeData()
            this.deptIds = this.timedProcessForm.userRange
          }
        }
        this.timedProcessForm.modelId = row.modelId
        this.timedProcessOpen = true
      } catch (error) {
        console.log(error);
      }

    },
    userClose() {
      this.userOpen = false
    },
    userOpenFun() {
      this.userOpen = true
    },
    handleUserOrDept(val) {
      if (val.length) {
        const ids = []
        const names = []
        val.forEach(item => {
          ids.push(item.userId)
          names.push(item.nickName)
        })
        this.timedProcessForm.userRange = ids
        this.timedProcessForm.userRangeName = names.toString()
      } else {
        this.$message.error('请选择用户')
      }
      this.userOpen = false
      // 用户确定
    },
    handleCronChange() {
      this.$refs["CronUi"].dialogVisible = true;
    },
    cronResultValue(data) {
      this.timedProcessForm = { ...this.timedProcessForm, crontab: data }
    },
    handleProcessRole(row) {
      this.openProcessRole = true;
      this.rowProcessRole = row;
    },
    /** 查询所属应用列表 */
    getCategoryList() {
      listCategory().then((response) => {
        this.categoryOptions = response.rows;
      });
    },
    /** 查询流程模型列表 */
    getList() {
      this.loading = true;
      let appId = this.$route.params && this.$route.params.appId;
      if (appId === undefined) {
        appId = this.appId;
      }

      listAppModel({
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        modelKey: null,
        modelName: this.queryParams.modelName,
        appId: appId,
      }).then((response) => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // listAppModel(appId).then(response => {
      //   this.modelList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    cancel() {
      this.reset();
      // 关闭dialog
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: undefined,
        modelKey: undefined,
        modelName: undefined,
        category: undefined,
        description: undefined,
        permitAppStartFlag: '1',
        permitAppAuditFlag: '1',
        cronFlag: '0'
      };
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.modelId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 部署流程 */
    handleDeploy(row) {
      this.loading = true;
      deployModel({
        modelId: row.modelId,
      })
        .then((response) => {
          this.$modal.msgSuccess(response.msg);
          this.loading = false;
          // let obj = { name: "Deploy", path: "/workflow/deploy" };
          // return this.$store
          //   .dispatch("tagsView/delCachedView", obj)
          //   .then(() => {
          //     this.$router.push(obj);
          //   });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 查看流程图 */
    handleProcessView(row) {
      let modelId = row.modelId;
      this.processView.title = "流程图";
      this.processView.index = modelId;
      // 发送请求，获取xml
      getBpmnXml(modelId).then((response) => {
        this.processView.xmlData = response.data;
      });
      this.processView.open = true;
    },
    getHistoryList() {
      this.history.loading = true;
      historyModel(this.queryHistoryParams).then((response) => {
        this.historyTotal = response.total;
        this.historyList = response.rows;
        this.history.loading = false;
      });
    },
    handleHistory(row) {
      this.history.open = true;
      this.queryHistoryParams.modelKey = row.modelKey;
      this.getHistoryList();
    },
    /** 设为最新版 */
    handleLatest(row) {
      this.$modal.confirm("是否确认将此版本设为最新？").then(() => {
        this.history.loading = true;
        latestModel({
          modelId: row.modelId,
        })
          .then((response) => {
            this.history.open = false;
            this.getList();
            this.$modal.msgSuccess(response.msg);
          })
          .finally(() => {
            this.history.loading = false;
          });
      });
    },
    handleCurrentChange(data) {
      if (data) {
        this.currentRow = JSON.parse(data.content);
      }
    },
    handleAdd() {
      this.title = "新增流程模型";
      const dateTime = new Date().getTime();
      this.form = {
        modelKey: `Process_${dateTime}`,
        modelName: `业务流程_${dateTime}`,
        category: "",
        permitAppStartFlag: '1',
        permitAppAuditFlag: '1',
        cronFlag: '0'
      };
      this.categoryOptions.forEach((item) => {
        if (item.categoryId === this.appId) {
          this.form.category = item.code;
        }
      });
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "修改流程模型";
      this.form = {
        modelId: row.modelId,
        modelKey: row.modelKey,
        modelName: row.modelName,
        category: row.category,
        description: row.description,
        permitAppAuditFlag: row.permitAppAuditFlag,
        permitAppStartFlag: row.permitAppStartFlag,
        cronFlag: row.cronFlag
      };
      this.open = true;
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.modelId !== undefined) {
            updateModel(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 设计按钮操作 */
    handleDesigner(row) {
      this.designerData.title = "流程设计 - " + row.modelName;
      this.designerData.modelId = row.modelId;
      this.designerData.modelKey = row.modelKey;
      this.designerData.appId = this.appId;
      this.designerData.form = {
        processName: row.modelName,
        processKey: row.modelKey,
      };
      if (row.modelId) {
        this.designerData.loading = true;
        getBpmnXml(row.modelId).then((response) => {
          this.designerData.bpmnXml = response.data || "";
          this.designerData.loading = false;
          this.designerOpen = true;
        });
      }
    },
    onSaveDesigner(
      bpmnXml,
      list,
      nodeList,
      interfaceList,
      titleField,
      tableName
    ) {

      let arr = [];
      if (Object.values(list)?.length) {
        Object.values(list).forEach((item) => {
          if (Array.isArray(item)) {
            arr = [...arr, ...item];
          }
        });
      }
      let nodeArr = [];
      if (Object.values(nodeList)?.length) {
        nodeArr = Object.values(nodeList);
      }
      nodeArr = nodeArr.filter((item) => !!item);
      const interfaceListParams = [];
      if (Object.values(interfaceList)?.length) {
        for (let key in interfaceList) {
          for (let keyChild in interfaceList[key]) {
            interfaceListParams.push({
              taskId: key,
              optType: keyChild,
              apiUrl: interfaceList[key][keyChild],
            });
          }
        }
      }

      this.bpmnXml = bpmnXml;
      let dataBody = {
        modelId: this.designerData.modelId,
        bpmnXml: this.bpmnXml,
      };
      this.$confirm("是否将此模型保存为新版本？", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "是",
        cancelButtonText: "否",
      })
        .then(() => {
          this.confirmSave(
            dataBody,
            true,
            arr,
            nodeArr,
            interfaceListParams,
            titleField,
            tableName
          );
          // let customFormDeptList = undefined;
          // if (window.bpmnInstances.bpmnElement?.businessObject?.flowElements) {
          //   customFormDeptList =
          //     window.bpmnInstances.bpmnElement?.businessObject?.flowElements;
          // } else {
          //   customFormDeptList =
          //     window.bpmnInstances.bpmnElement?.businessObject?.$parent
          //       ?.flowElements;
          // }
          // if(customFormDeptList?.length) {
          //  customFormDeptList.forEach(item=>{
          //     if(item.dataType && item.dataType === "FORMDEPT") {
          //       formDeptField
          //     }
          //   })
          // }
          // console.log(customFormDeptList);
        })
        .catch((action) => {
          // if (action === "cancel") {
          //   this.confirmSave(dataBody, false);
          // }
        });
    },
    async confirmSave(
      body,
      newVersion,
      list,
      nodeArr,
      interfaceListParams,
      titleField,
      tableName
    ) {
      this.designerData.loading = true;
      try {
        await saveModel(
          Object.assign(body, {
            newVersion: newVersion,
          })
        );
        if (list.length) {
          await appProcessFormset(list);
        }
        if (nodeArr.length) {
          await saveNodeApproverProcess(nodeArr);
        }
        if (interfaceListParams.length) {
          await saveNodeInterface(interfaceListParams);
        }
        if (!!titleField.fieldTitle?.length && !!tableName) {
          await saveAppProcessTitleConfig({
            processKey: this.designerData.modelKey,
            titleField: JSON.stringify(titleField.fieldTitle),
            tableName,
          });
        }

        this.designerOpen = false;
        this.designerData.loading = false;
        this.$message.success("保存成功");
        this.getList();
      } catch (error) {
        this.designerData.loading = false;
      }
      // saveModel(Object.assign(body, {
      //   newVersion: newVersion
      // })).then(() => {

      // }).finally(() => {

      // })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.loading = true;
      delModel(modelIds).then((res) => {
        if (res.code === 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.loading = false;
        }
      }).finally(() => {
        this.loading = false;
      });
      // this.$modal
      //   .confirm('是否确认删除模型编号为"' + modelIds + '"的数据项？')
      //   .then(() => {
      //     this.loading = true;
      //     return delModel(modelIds);
      //   })
      //   .then(() => {
      //     this.loading = false;
      //     this.getList();
      //     this.$modal.msgSuccess("删除成功");
      //   })
      //   .finally(() => {
      //     this.loading = false;
      //   });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workflow/model/export",
        {
          ...this.queryParams,
        },
        `wf_model_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入bpmn.xml文件 */
    handleImport() {
      this.upload.title = "bpmn20.xml文件导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$message.success(response.msg);
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
    categoryFormat(row, column) {
      return (
        this.categoryOptions.find((k) => k.code === row.category)
          ?.categoryName ?? ""
      );
    },
    submitSave() {
      this.getList();
    },
  },
};
</script>
<style scoped lang="scss">
.topBtn {
  display: flex;
  justify-content: space-between;
  align-items: center;

  ::v-deep .input-with-select {
    width: 300px;
  }

  ::v-deep .el-icon-search {
    color: #fff;
  }
}
</style>
